package club.banyuan;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SharedCounter extends Thread {
    static int counter = 0;
    public int num;

    public SharedCounter(int numIncrementsPerThread) {
        num = numIncrementsPerThread;
    }

    @Override
    public void run() {
        synchronized (this) {
            counter += num;
        }
    }

    public static void reset() {
        counter = 0;
    }

    public static int increment(int numThreads, int numIncrementsPerThread) throws InterruptedException {
        List<SharedCounter> sharedCounters = new ArrayList<>();
        for (int i = 0; i < numThreads; i++) {
            SharedCounter sharedCounter = new SharedCounter(numIncrementsPerThread);
            sharedCounters.add(sharedCounter);
            sharedCounter.start();
//            Thread.sleep(5);
        }

        for (SharedCounter sharedCounter : sharedCounters) {
            sharedCounter.join();
        }

        return counter;
    }
}
